#!/bin/sh

hex2rgb() {
    set -- "${1##\#}"

    r=${1%%????}
    g=${1##??}
    g=${g%%??}
    b=${1##????}

    r=$((0x$r))
    g=$((0x$g))
    b=$((0x$b))
}

printf '\n'

set -- `
    convert "$1" \
        -alpha off \
        -posterize 7  \
        -fill white \
        -unique-colors \
        txt:- |

    while IFS='# ' read -r _ _ col _; do
        i=$((i+1))

        [ "$i" -lt 2 ] && continue
        
        printf '%s\n' "$col"
    done
`

shift "$(($# - 8))"

for c do 
    i=$((i+1))
    hex2rgb "$c"

    printf '\033[48;2;%s;%s;%sm   \033[m ' "$r" "$g" "$b"

    [ "$((i % 8))" = 0 ] && printf '\n'
done
printf '\n\n'
